<template>
  <div class="vuewaterfall" :style="{height:position && position[0].top + 'px'}">
    <slot></slot>
  </div>
</template>

<script>
export default {
  props: {
    // 起始top值
    top: {
      type: Number,
      default: 0
    },
    // 起始left值
    left: {
      type: Number,
      default: 0
    },
    // 上下间隔
    topInterval: {
      type: Number,
      default: 20
    },
    // 左右间隔
    leftInterval: {
      type: Number,
      default: 20
    },
    // 瀑布流每个的宽度
    width: {
      type: Number,
      required: true
    },
    // 瀑布流没列个数
    rowNumber: {
      type: Number,
      required: true
    }
    // 瀑布流数据
    /* data:{
                type:Array,
                required: true
            } */
  },
  data() {
    return {
      position: null
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.waterFall()
    })
  },
  methods: {
    // 初始数据
    initData() {
      return new Array(this.rowNumber).fill(undefined).map((item, index) => {
        return {
          top: this.top,
          left: this.left + (this.width + this.leftInterval) * index
        }
      })
    },
    // 计算瀑布流dom位置
    waterFall() {
      let initData = this.initData()
      this.$children.forEach(item => {
        let dom = item.$el
        initData.sort((a, b) => {
          return a.top - b.top
        })
        dom.style.top = initData[0].top + "px"
        dom.style.left = initData[0].left + "px"
        initData[0].top += dom.offsetHeight + 20
      })
      initData.sort((a, b) => {
        return b.top - a.top
      })

      this.position = initData
    }
  }
}
</script>

<style lang="less" scoped>
.vuewaterfall {
  position: relative;
}
</style>
